package com.cby.operation.common.widget.richtext

import android.annotation.SuppressLint
import android.content.Context
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.util.AttributeSet
import android.widget.TextView

/**
 * 适配行间距不一致问题
 *
 * @author 徐智伟
 * @create 2020-03-27
 */
@SuppressLint("AppCompatCustomView")
class LineSpaceExtraTextView : TextView {
    constructor(context: Context?) : super(context) {}
    constructor(context: Context?,
                attrs: AttributeSet?) : super(context, attrs) {
    }

    constructor(context: Context?, attrs: AttributeSet?,
                defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
    }

    /**
     * 排除每行文字间的padding
     *
     * @param text
     */
    fun setCustomText(text: CharSequence?) {
        if (text == null) {
            return
        }

        // 获得视觉定义的每行文字的行高
        val lineHeight = textSize.toInt()
        val ssb: SpannableStringBuilder
        if (text is SpannableStringBuilder) {
            ssb = text
            // 设置LineHeightSpan
            ssb.setSpan(ExcludeInnerLineSpaceSpan(lineHeight),
                    0, text.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        } else {
            ssb = SpannableStringBuilder(text)
            // 设置LineHeightSpan
            ssb.setSpan(ExcludeInnerLineSpaceSpan(lineHeight),
                    0, text.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        }

        // 调用系统setText()方法
        setText(ssb)
    }
}